﻿using MyCompany.MyProject.Common.Core;
using MyCompany.MyProject.Model.Models.RootKey;
using MyCompany.MyProject.Model.Models.Tenants;
using SqlSugar;


namespace MyCompany.MyProject.Common.DB;

public class RepositorySetting
{
    /// <summary>
    /// 配置租户
    /// </summary>
    /// <param name="db"></param>
    public static void SetTenantEntityFilter(SqlSugarScopeProvider db)
    {
        if (App.User is not { ID: > 0, TenantId: > 0 })
        {
            return;
        }

        // 多租户 单表字段
        db.QueryFilter.AddTableFilter<ITenantEntity>(i => i.TenantId == App.User.TenantId || i.TenantId == 0);

       
        // 多表多租户
        db.SetTenantTable(App.User.TenantId.ToString());
    }

    private static readonly Lazy<IEnumerable<Type>> AllEntitys = new Lazy<IEnumerable<Type>>(() =>
    {
        return typeof(RootEntityTKey<>).Assembly.GetTypes()
        .Where(t => t.IsClass && !t.IsAbstract)
        .Where(i => i.FullName != null && i.FullName.StartsWith("MyCompany.MyProject.Model"));
    });

    /// <summary>
    /// 获取所有的符合多租户条件的表
    /// </summary>
    public static IEnumerable<Type> Entitys => AllEntitys.Value;
}
